<script>
  import {
    SSEWebSocket
  } from '@/utils/websocket.js';
  import {
    createMessage
  } from '@/utils/websocketMessages.js';
  import {
    createNotification,
    handleNotification
  } from '@/utils/notification.js';

  export default {
    data() {
      return {
        sseClient: null,
        eventManager: null,
        isEventBusReady: false,
        isPlusReady: false,
        isAppInBackground: false, // 应用是否在后台
        currentPage: '' // 当前页面路径
      };
    },

    onLaunch() {
      // WebSocket 初始化
      const accessToken = uni.getStorageSync('deviceNo');
      this.sseClient = new SSEWebSocket(accessToken);
      getApp().globalData = getApp().globalData || {};
      getApp().globalData.sseClient = this.sseClient;

      this.sseClient.on('message', (msg) => {
        console.log('【收到消息】', msg);
        this.handleMessage(msg);
      });
      this.sseClient.on('open', () => console.log('WebSocket已连接'));
      this.sseClient.on('close', (res) => console.log('WebSocket已关闭:', res));
      this.sseClient.on('error', (err) => console.error('WebSocket错误:', err));

      // 监听plusready后注册事件总线
      if (typeof document !== 'undefined') {
        document.addEventListener('plusready', () => {
          console.log('plusready 事件触发');
          this.isPlusReady = true;
          this.setupEventBus();
          this.setupAppStateListener();
          handleNotification();
        }, {
          once: true
        });
      } else {
        setTimeout(() => {
          console.log('延迟设置事件总线');
          this.isPlusReady = true;
          this.setupEventBus();
          this.setupAppStateListener();
          handleNotification();
        }, 500);
      }
    },

    onShow() {
      // 应用从后台回到前台
      this.isAppInBackground = false;
      console.log('[应用状态] 应用已回到前台');

      if (this.isPlusReady && !this.isEventBusReady) {
        this.setupEventBus();
      }
      if (this.isPlusReady) {
        handleNotification();
      }
    },

    onHide() {
      // 应用进入后台
      this.isAppInBackground = true;
      console.log('[应用状态] 应用已进入后台');
    },

    onUnload() {
      // 关闭WebSocket
      if (this.sseClient && this.sseClient.isConnected) {
        try {
          const exitMessage = createMessage('EXIT');
          this.sseClient.send(exitMessage);
          console.log('已发送应用退出通知消息:', exitMessage);
        } catch (e) {
          console.error('发送退出通知消息失败:', e);
        }
      }
      if (this.sseClient) {
        this.sseClient.close();
        console.log('WebSocket已手动关闭');
      }

      // 清理事件总线
      if (this.eventManager) {
        try {
          this.eventManager.unregisterListener('hardware_key', this.onHardwareKeyEvent);
          console.log('[EventBus] 事件监听器已注销');
        } catch (e) {
          console.error('注销事件监听器失败:', e);
        } finally {
          this.eventManager = null;
          this.isEventBusReady = false;
          this.isPlusReady = false;
        }
      }
    },

    methods: {
      // 设置事件总线
      setupEventBus() {
        console.log('[EventBus] 开始设置事件总线');

        if (!this.isPlusReady || this.isEventBusReady) {
          console.log('[EventBus] 跳过设置');
          return;
        }

        try {
          if (plus.os.name !== 'Android') {
            console.log('[EventBus] 非Android平台，无法设置事件总线');
            return;
          }

          console.log('[EventBus] 获取事件管理器');

          const mainActivity = plus.android.runtimeMainActivity();
          const eventManagerClass = plus.android.importClass('uni.app.UNIDB65BBB.MyEventManager');

          console.log('[EventBus] 事件管理器类:', eventManagerClass);

          const eventCallback = plus.android.implements('uni.app.UNIDB65BBB.MyEventManager$EventCallback', {
            onEvent: (source, data) => {
              console.log('[EventBus] 收到事件:', source, data);
              this.onHardwareKeyEvent(source, data);
            }
          });

          console.log('[EventBus] 事件回调已创建');

          eventManagerClass.registerListener('hardware_key', eventCallback);
          console.log('[EventBus] 事件监听器已注册');

          this.eventManager = {
            class: eventManagerClass,
            callback: eventCallback
          };

          this.isEventBusReady = true;
          console.log('[EventBus] 事件总线设置成功');

        } catch (e) {
          console.error('[EventBus] 设置失败:', e);
          this.isEventBusReady = false;
          this.eventManager = null;
        }
      },

      // 处理硬件按键事件
      onHardwareKeyEvent(source, data) {
        try {
          console.log('[EventBus] 收到按键事件:', source, data);

          // 解析事件数据
          const payload = {
            vendorAction: data.vendorAction || '未知',
            timestamp: data.timestamp || Date.now(),
            nativePid: data.nativePid || '未知',
            source: source,
            keyStatus: data.keyStatus || '未知',
            keyDescription: data.keyDescription || '未知按键',
            packageName: data.packageName || '未知',
            appVersion: data.appVersion || '未知',
            androidVersion: data.androidVersion || '未知',
            deviceModel: data.deviceModel || '未知',
            broadcastExtras: data.broadcastExtras || {},
            debugInfo: data.debugInfo || {}
          };

          // 1) 按键后直接拉起页面（前台时立即生效；后台时可能被系统拦截）
          this.navigateToIntercom(payload);

          // 2) 同时发起通知，便于在应用处于后台/锁屏时，用户点击通知将应用唤到前台并跳转
          createNotification('点击进入语音对讲', payload, {
            title: '语音对讲',
            content: '正在呼叫中....'
          }, '/pages/intercom/intercom', '/static/Audio/calling.mp3');

          // 业务派发
          uni.$emit('hardware-key', payload);

        } catch (e) {
          console.error('[EventBus] 处理事件失败:', e);
        }
      },

      // 导航到intercom页面
      navigateToIntercom(payload) {
        try {
          uni.navigateTo({
            url: '/pages/intercom/intercom',
            success: () => {
              console.log('[导航] 成功跳转到intercom页面');
              getApp().globalData.currentKeyEvent = payload;
            },
            fail: (err) => {
              console.error('[导航] 跳转失败:', err);
            }
          });
        } catch (e) {
          console.error('[导航] 导航异常:', e);
        }
      },

      // 设置应用状态监听
      setupAppStateListener() {
        if (!this.isPlusReady) {
          console.log('[应用状态] plus未就绪，跳过状态监听设置');
          return;
        }

        try {
          // 监听应用状态变化
          document.addEventListener('visibilitychange', () => {
            if (document.hidden) {
              this.isAppInBackground = true;
              console.log('[应用状态] 应用进入后台 (visibilitychange)');
            } else {
              this.isAppInBackground = false;
              console.log('[应用状态] 应用回到前台 (visibilitychange)');
            }
          });

          // Android平台特定的应用状态监听
          if (plus.os.name === 'Android') {
            const mainActivity = plus.android.runtimeMainActivity();
            const Intent = plus.android.importClass('android.content.Intent');
            const ActivityManager = plus.android.importClass('android.app.ActivityManager');

            // 监听应用生命周期
            mainActivity.addEventListener('pause', () => {
              this.isAppInBackground = true;
              console.log('[应用状态] 应用暂停 (Android)');
            });

            mainActivity.addEventListener('resume', () => {
              this.isAppInBackground = false;
              console.log('[应用状态] 应用恢复 (Android)');
            });
          }

          console.log('[应用状态] 应用状态监听器已设置');
        } catch (e) {
          console.error('[应用状态] 设置状态监听失败:', e);
        }
      },



      // WebSocket消息处理
      handleMessage(msg) {
        console.log('处理消息:', msg);
      }
    }
  };
</script>

<style>
  * {
    box-sizing: border-box;
  }

  ::-webkit-scrollbar {
    display: none !important;
    width: 0 !important;
    height: 0 !important;
  }
</style>